//
//  WBTabBar.swift
//  WB123
//
//  Created by xuyunde mac pro on 2017/6/29.
//  Copyright © 2017年 NSObjiect. All rights reserved.
//

import UIKit

// 声名协议
protocol WBTabBarDelegate:NSObjectProtocol{
    // 声名协议方法
    func composeButtonSelect()
}

class WBTabBar: UITabBar {
    
    // 01声名闭包******************************
    var closure:(()->())?
    
    // 声名代理
    weak var wbdelegate:WBTabBarDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // 执行监听方法也就是执行闭包,这个方法由MainVCUITabBarController来监听所以闭包02实例化 04回调闭包写在UITabBarController里 
    @objc private func composeButtonClick(){
        
        // 01 声名闭包 和 03执行闭包不分家*************************
//        closure?()
//         print("点击了111")
        
        // 代理方法执行
        wbdelegate?.composeButtonSelect()
    }
    
    // 视图
    private func setupUI(){
        addSubview(composeButton)
    }
    override func layoutSubviews() {
        super.layoutSubviews()//-----------父类布局------
        //设置宽度
        let w = frame.width * 0.2
        var index: CGFloat = 0
        // 遍历子控件
        for view in subviews {
            // UITabBarButton根据字符串转出,决定对应的子控件类型从而判断是否是想要的子控件*******************************************
            if view.isKind(of: NSClassFromString("UITabBarButton")!) {
                
                view.frame.size.width = w
                view.frame.origin.x = w * index
                
                index += 1
                
                //如果index=2在加一
                if index == 2 {
                    index += 1
                }
            }
        }
        // 设置frame
        composeButton.center.x = frame.size.width * 0.5
        composeButton.center.y = frame.size.height * 0.5
    }
    //懒加载创建btn
    private lazy var composeButton: UIButton = {
        let btn = UIButton()
        
        btn.addTarget(self, action: #selector(composeButtonClick), for: UIControlEvents.touchUpInside)
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
        
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: UIControlState.normal)
        btn.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted)
        
            btn.setImage(UIImage(named:"tabbar_compose_icon_add"), for: UIControlState.normal)
        btn.sizeToFit()
        return btn
    }()
}
